package com.hospital.hospitalserver.service;

import com.hospital.hospitalserver.entity.Vo.BaseUser;
import com.hospital.hospitalserver.util.EncryptHelper;
import com.hospital.hospitalserver.util.Response;
import com.hospital.hospitalserver.entity.UserInfo;
import com.hospital.hospitalserver.enums.ResultCodeEnum;
import com.hospital.hospitalserver.mapper.UserMapper;
import com.hospital.hospitalserver.util.TokenUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * 用户模块实现类
 * */
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserMapper userMapper;
    /**
     * 定义方法
     * 用户登录
     * */
    public Response validateUser(UserInfo user){
        // 1. 验证用户是否存在
        UserInfo u = userMapper.findUserByUsername(user);
        if(u==null){
            System.out.println(1);
            return Response.error(ResultCodeEnum.LOGIN_ERROR);
        }

        // 2. 验证密码（这里使用MD5加密验证，实际应根据安全要求选择加密方式）
        String encryptedPassword = EncryptHelper.SHA(user.getUserpass());
//        System.out.println(encryptedPassword);
        if(!u.getUserpass().equals(encryptedPassword)){
            System.out.println(2);
           return Response.error(ResultCodeEnum.LOGIN_ERROR);
        }

        // 3. 检查用户是否激活
        if(u.getIs_active()!=1){
            return Response.error(ResultCodeEnum.LOGIN_ERROR);
        }

        // 4. 根据角色类型获取不同的详细信息
        Object userData;
        BaseUser baseUser = userMapper.findBaseUserByUsername(user);
        String roleName = baseUser.getRole_name(); // 需要先获取角色名称

        switch (roleName){
            case "doctor":
                userData = userMapper.findDoctorDetailByUsername(user);
                break;
            case "nurse":
                // 可以添加护士的查询逻辑
                userData = userMapper.findNurseDetailByUsername(user);
                break;
            case "admin":
                // 可以添加行政人员的查询逻辑
                userData = userMapper.findManagerDetailByUsername(user);
                break;
            case "pharmacist":
                // 可以添加药剂师的查询逻辑
                userData = userMapper.findPharmacistDetailByUsername(user);
                break;
            case "finance":
                // 可以添加财务人员的查询逻辑
                userData = userMapper.findFinanceDetailByUsername(user);
                break;
            default:
                userData = baseUser;
        }
        String token = TokenUtils.sign(user);
        HashMap<String,Object> hs = new HashMap<>();
        hs.put("token",token);
        hs.put("role",roleName);
        hs.put("user",userData);

        return Response.success(ResultCodeEnum.LOGIN_SUCCESS,hs);
    }
}
